package com.jackstraw.jack_base.rules.threadpool;


import cn.hutool.core.thread.NamedThreadFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 执行器初始化线程池
 * 1.初始化场景任务
 * 2.初始化规则代码
 */
public class ExcuteInitThreadPool {

    /**
     * 綫程池对象，单例
     */
    private static volatile ExecutorService EXECUTORSERVICE;

    /**
     * 核心线程的大小
     */
    private static final int CORE = 5;
    /**
     * 最大线程个数
     */
    private static final int MAX = 15;
    /**
     * 队列排队等待线程个数
     */
    private static final int WAIT = 500;
    /**
     * 綫程空閑時存活时间（单位秒）
     */
    private static final long IDEL = 2L;
    /**
     * 线程池中的线程别名
     */
    private static final String ALIASNAME = "ExcuteInitThreadPool-%d";

    /**
     * 单例模式创建线程池
     */
    private static void createFactoryExecutor() {
        synchronized (ExcuteInitThreadPool.class) {
            if (null == EXECUTORSERVICE) {
                EXECUTORSERVICE = new ThreadPoolExecutor(CORE, MAX, IDEL,
                        TimeUnit.SECONDS, new LinkedBlockingDeque<>(WAIT),
                        new NamedThreadFactory(ALIASNAME, Boolean.FALSE), new ExecutionHandler());
            }
        }
    }

    public static void submitTask(final Runnable runnable) {
        if (null == EXECUTORSERVICE) {
            createFactoryExecutor();
        }
        EXECUTORSERVICE.submit(runnable);
    }


}
